import { createApp } from 'vue';

// 创建一个空的Vue应用作为事件总线
const emitter = createApp({});

// 添加Vue 2风格的API以兼容现有代码
emitter.$on = function(event, callback) {
  this._events = this._events || {};
  this._events[event] = this._events[event] || [];
  this._events[event].push(callback);
  return this;
};

emitter.$once = function(event, callback) {
  const vm = this;
  function on() {
    vm.$off(event, on);
    callback.apply(vm, arguments);
  }
  on.fn = callback;
  vm.$on(event, on);
  return vm;
};

emitter.$off = function(event, callback) {
  const vm = this;
  // 所有事件
  if (!arguments.length) {
    vm._events = Object.create(null);
    return vm;
  }
  // 特定事件
  if (Array.isArray(event)) {
    for (let i = 0; i < event.length; i++) {
      vm.$off(event[i], callback);
    }
    return vm;
  }
  // 特定事件的特定回调
  const cbs = vm._events[event];
  if (!cbs) {
    return vm;
  }
  if (!callback) {
    vm._events[event] = null;
    return vm;
  }
  let cb;
  let i = cbs.length;
  while (i--) {
    cb = cbs[i];
    if (cb === callback || cb.fn === callback) {
      cbs.splice(i, 1);
      break;
    }
  }
  return vm;
};

emitter.$emit = function(event) {
  const vm = this;
  if (vm._events && vm._events[event]) {
    const cbs = vm._events[event].slice();
    const args = Array.prototype.slice.call(arguments, 1);
    for (let i = 0, l = cbs.length; i < l; i++) {
      try {
        cbs[i].apply(vm, args);
      } catch (e) {
        console.error(e);
      }
    }
  }
  return vm;
};

// 添加兼容别名，支持on/off/emit方法
emitter.on = emitter.$on;
emitter.once = emitter.$once;
emitter.off = emitter.$off;
emitter.emit = emitter.$emit;

export default emitter; 